import { _decorator, Component, director, Label, Node, SceneAsset, Sprite, Tween, tween } from 'cc';
import { ClientAPI } from '../src/api/client.api';
import { GameData } from '../Data/GameData';
import { NCPoint } from '../src/api/api.config.client';
import { UserData } from '../Data/UserData';
import InitData from './InitData';
import { LocalStorageMgr } from '../Mgr/LocalStorageMgr';
const { ccclass, property } = _decorator;

@ccclass('Loading')
export class Loading extends Component {

    @property(Sprite)
    private progressBar: Sprite = null;
    @property(Label)
    private progressLabel: Label = null;
    @property(Node)
    private bg: Node = null;

    fakeProgress: number;
    // 将 fakeProgress 存储在一个对象中，便于 Tween 动画操作
    private progressData = { fakeProgress: 0 };
    // 用于标记场景是否加载完成
    private sceneLoaded: boolean = false;



    private timeoutId: any = null;

    private readonly delay = 10000; // 10秒的延迟

    protected onLoad() {
        this.preloadScene('main');
        InitData.init();
        this.startTimer();
    }

    start() {
        ClientAPI.CloseLoading();
        mtec.cc.adaptBackgroundNode(this.bg);
        this.updateProgress(0.95);
        InitData.userDataLoaded.then(success => {
            this.enterGame('main');
        });
    }

    update(deltaTime: number) {

    }

    public startTimer() {
        // 确保没有已有的定时器
        if (this.timeoutId === null) {
            this.timeoutId = setTimeout(() => {
                console.log('异常');

                LocalStorageMgr.clear();
                InitData.init();
                InitData.userDataLoaded.then(success => {
                    this.enterGame('main');
                    this.resetTimer(); // 执行完后重置计时器
                });




            }, this.delay);
        }
    }
    public resetTimer() {
        // 取消已有定时器
        if (this.timeoutId !== null) {
            clearTimeout(this.timeoutId);
            this.timeoutId = null;
        }
    }

    preloadScene(sceneName: string): void {
        if (!GameData.data.gameInitFinish) {
            ClientAPI.Point(NCPoint.GAMEINITSTART, { userid: UserData.data.userId });
        }
        // 初始化假的进度条为0
        this.progressData.fakeProgress = 0;
        this.sceneLoaded = false; // 重置场景加载标志

        // 预加载场景
        director.preloadScene(sceneName, this.onProgress.bind(this), (err, sceneAsset: SceneAsset) => {
            if (err) {
                console.error(`Failed to load scene: ${sceneName}`, err);
                return;
            }

            // 场景加载完成，标记为已加载
            this.sceneLoaded = true;
            // // 如果Tween已经完成，则立即完成进度条
            // if (this.progressData.fakeProgress >= 0.9) {
            //     this.completeLoading(sceneName); // 完成加载并切换场景
            // }
        });
    }

    private onProgress(completedCount: number, totalCount: number): void {

    }

    private updateProgressBar(): void {
        // 更新进度条显示
        if (this.progressBar && this.progressBar.fillRange < 1) {
            this.progressBar.fillRange = this.progressData.fakeProgress;
            this.progressLabel.string = Math.floor(this.progressData.fakeProgress * 100) + '%';
        }
    }

    private completeLoading(sceneName): void {
        // 当Tween动画完成并且场景加载完毕后，将进度条快速填充到100%
        Tween.stopAllByTarget(this.progressData);
        tween(this.progressData)
            .to(1, { fakeProgress: 1 }, {
                onUpdate: () => {
                    this.updateProgressBar(); // 更新进度条显示
                },
                onComplete: () => {
                    // 最终完成，切换场景
                    this.scheduleOnce(() => {
                        director.loadScene(sceneName, (err) => {
                            if (err) {
                                console.error(`Failed to switch to scene: main`, err);
                            } else {
                                console.log(`Scene main loaded successfully!`);
                            }
                        });
                    }, 0.1); // 延迟切换场景
                }
            })
            .start();
    }

    public updateProgress(targetProgress: number) {
        console.log('更新loading进度条');

        Tween.stopAllByTarget(this.progressData);
        tween(this.progressData)
            .to(3, { fakeProgress: targetProgress }, {
                onUpdate: () => {
                    this.updateProgressBar();
                }
            })
            .start();
    }

    public enterGame(sceneName: string) {
        this.resetTimer();
        this.completeLoading(sceneName);
    }
}

